package daoImp;

import Util.FileIOUtil;
import dao.ManagerDao;
import entity.Manager;

import java.io.File;
import java.util.ArrayList;

public class ManagerDaoImp implements ManagerDao {
    FileIOUtil fio = new FileIOUtil();
    String managersFile = "managers";
    public ManagerDaoImp(){
        if (fio.input(managersFile).size()==0){
            addManager(new Manager(0,0,"000"));
        }
    }
    @Override
    public ArrayList<Manager> getManagers() {
        ArrayList<Manager> al;
        al = fio.input(managersFile);
        return al;
    }

    @Override
    public Manager getManager(int mid) {
        ArrayList<Manager> al = getManagers();
        if (al.size()==0)
            return null;
        for (Manager m:al
             ) {
            if (m.getMid()==mid){
                return m;
            }
        }
        return null;
    }

    @Override
    public boolean addManager(Manager manager) {
        ArrayList<Manager> al = getManagers();
        boolean isOk = al.add(manager);
        boolean isOk2 = fio.output(managersFile,al);
        return isOk&&isOk2;
    }

    @Override
    public boolean login(int mid, String pwd) {
        Manager m = getManager(mid);
        if (m==null)
            return false;
        if (m.login(pwd))
            return true;
        return false;
    }

    @Override
    public boolean changePwd(int mid,String newPwd) {
        if (getManager(mid)==null)
            return false;
        ArrayList<Manager> al = getManagers();
        for (int i = 0; i < al.size(); i++) {
            if (al.get(i).getMid()==mid)
                al.get(i).setPwd(newPwd);
        }
        return true;
    }

    @Override
    public int getId() {
        ArrayList<Manager> al = getManagers();
        int x = al.size();
        boolean flag = false;
        for (int i = 0; i < x; i++) {
            flag = false;
            for (Manager e:al
            ) {
                if (e.getMid()==i){
                    flag = true;
                }
            }
            if (!flag){
                x = i;
                break;
            }
        }
        return x;
    }
}
